package com.yanqu.road.server.timer.dunhuangshiku;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.pb.dunhuangshiku.DunHuangShiKuProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.cross.battle.dunhuangshiku.DunHuangShiKuActivity;
import com.yanqu.road.server.manager.cross.battle.dunhuangshiku.DunHuangShiKuActivityGroup;
import com.yanqu.road.server.manager.cross.battle.dunhuangshiku.DunHuangShiKuMgr;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 敦煌石窟 获取活跃玩家数据
 */
public class CrossDunHuangShiKuGetActiveUserInfoTask extends GeneralTask {

    @Override
    public void doRun() {
        Map<Integer, DunHuangShiKuActivityGroup> activityGroupMap = DunHuangShiKuMgr.getActivityGroupMap();
        Set<Long> sendServer = new HashSet<>(); // 已发送的服务器
        for (DunHuangShiKuActivityGroup activityGroup : activityGroupMap.values()) {
            for (DunHuangShiKuActivity item : activityGroup.getActivityMap().values()) {
                List<Long> serverList = item.getNeedSynActiveUserInfo();
                int activityId = item.getActivityId();
                Map<Integer, DunHuangShiKuActivity> activityMap = DunHuangShiKuMgr.getActivityGroupMap().get(activityId).getActivityMap();
                if (activityMap.isEmpty()) {
                    continue;
                }
                Map.Entry<Integer, DunHuangShiKuActivity> kv = activityMap.entrySet().iterator().next();
                DunHuangShiKuActivity activity = kv.getValue();
                if (activity == null) {
                    continue;
                }
                int loginTime = (int) (DateHelper.getTodayZeroTime() - item.getDUNHUANGSHIKU_ACTIVE_DAYS() * DateHelper.DAY_SECONDS);
                DunHuangShiKuProto.DunHuangShiKuSynActiveUserInfoToGameServerMsg.Builder builder = DunHuangShiKuProto.DunHuangShiKuSynActiveUserInfoToGameServerMsg.newBuilder();
                builder.setActivityId(activity.getActivityId());
                builder.setLastLoginTime(loginTime);
                for (long serverId : serverList) {
                    if (sendServer.contains(serverId)) {
                        continue;
                    }
                    sendServer.add(serverId);
                    MessageHelper.sendPacket(serverId, -1, YanQuMessageUtils.buildMessage(GameProtocol.S_DUN_HUANG_SHI_KU_GET_ACTIVE_USER_INFO_FROM_CROSS, builder));
                }
                DunHuangShiKuMgr.getLogger().info("向区服 获取活跃玩家数据 loginTime:{}, 活跃玩家数据info:{}", loginTime, JSON.toJSONString(serverList));
            }
        }
    }
}
